<script lang="ts" setup>
import { useVModel } from '@vueuse/core'
import { computed, defineComponent, reactive, ref, watch } from 'vue'
import to from '@/utils/awaitTo'
import Api from '@/api/'
import { message } from 'ant-design-vue' // 引入Antd
import { cloneDeep } from 'lodash-es'
import { QuestionCircleTwoTone } from '@ant-design/icons-vue'
import { UploadImage } from '@/components/basic/Upload'

// 声明参数
const props = defineProps({
  // 标题
  data: {
    type: Object,
    default: () => {
    }
  },

  // 开关
  open: {
    type: Boolean,
    required: true
  }
})

// 自定义组件
const VNodes = defineComponent({
  props: {
    vnodes: {
      type: Object,
      required: true
    }
  },
  render() {
    return this.vnodes
  }
})

// 声明方法
const emit = defineEmits(['update:open', 'callback'])

// 双向绑定方法
const openVModel = useVModel(props, 'open', emit)

// 规则
const rules = {}

// 表单实例
const formRef = ref()

// 菜单权限实例
const treeRef = ref()

// 用户信息
const FormData = computed(() => {
  return props.data
})

/** 多选限制 */
const handleOnChange = async (values) => {
  const list = cloneDeep(FormData.value.roleIds)
  FormData.value.roleIds = list.filter((item) => item === values)
}

/** 回显角色列表 */
const cashbackData = reactive({
  data: null,
  loading: false
})
const getRoleUserEcho = async () => {
  cashbackData.loading = true
  const [error, data] = await to(Api.user.userEchoList())
  cashbackData.loading = false
  if (!error) {
    cashbackData.data = data
  }
}


/** 回显 科室 医院 */
// 医院科室列表回显
const hosdepData = reactive({
  queryParams: {
    hospitalName: '',
    classificationName: '',
    parentId: '0'
  },
  hospitalList: [],
  sectionList: [],
  loading: false,
  parentId: ''
})
const getEchoHospitalDepartment = async () => {
  hosdepData.loading = true
  const [error, data] = await to(Api.user.userEchoDP(hosdepData.queryParams))
  if (!error) {
    hosdepData.loading = false
    hosdepData.hospitalList = data.meereenHospitals // 医院列表
    hosdepData.sectionList = data.meereenClassifications // 科室列表
    hosdepData.parentId = data.parentId // 父级id
  }
}
const handleAddHospital = () => {
  // if (!hosdepData.value.queryParams.hospitalName) {
  //   toast(`请输入要新增的医院`);
  //   return;
  // }
  // hosdepData.value.loading = true;
  // const { code, data, success } = await userlist_addhospital_api(
  //   hosdepData.value.queryParams
  // )
  //   .catch((error) => {
  //     console.log(error);
  //   })
  //   .finally(() => {
  //     hosdepData.value.loading = false;
  //   });
  //
  // if (code === 200 && success) {
  //   const { hospitalId } = data;
  //   await getEchoHospitalDepartment();
  //   FormData.value.hospitalId = hospitalId;
  //   hosdepData.value.queryParams.hospitalName = "";
  //   toast(`新增医院成功`);
  // }
}
// 新增科室事件
const handleAddSection = async () => {
  // if (!hosdepData.value.queryParams.classificationName) {
  //   toast(`请输入要新增的科室`);
  //   return;
  // }
  //
  // hosdepData.value.loading = true;
  // const { code, data, success } = await userlist_addClassification_api(
  //   hosdepData.value.queryParams
  // )
  //   .catch((error) => {
  //     console.log(error);
  //   })
  //   .finally(() => {
  //     hosdepData.value.loading = false;
  //   });
  //
  // if (code === 200 && success) {
  //   const [ids] = Object.keys(data);
  //   await getEchoHospitalDepartment();
  //   FormData.value.classificationId = ids;
  //   hosdepData.value.queryParams.classificationName = "";
  //   toast(`新增科室成功`);
  // }
}


const handleUserSubmit = (formEl) => {
  if (!formEl) return
  formEl
    .validate()
    .then(async (values) => {
      const checkedKeys = treeRef.value.checkedKeys
      const halfCheckedKeys = treeRef.value.halfCheckedKeys

      const params = Object.assign({}, values, FormData.value, {
        menuIds: [...checkedKeys, ...halfCheckedKeys]
      })

      console.log(params)

      // 修改
      if (params.userId) {
        console.log(params)
        const [error, data] = await to(Api.user.userEdit(params))
        if (!error) {
          message.success('操作成功')
          openVModel.value = false
          emit('callback')
          console.log(data)
        }
      }

      // 新增
      else {
        const [error, data] = await to(Api.user.userAddUser(params))
        if (!error) {
          message.success('操作成功')
          openVModel.value = false
          emit('callback')
          console.log(data)
          console.log(data)
        }
      }


    })
    .catch((error: Error) => {
      console.log(error)
    })
}


// 监听角色改变事件
watch(
  () => FormData.value.roleIds,
  async (newVal) => {
    if (newVal && newVal.length) {
      const [error, data] = await to(Api.user.userEchoRoles(newVal))
      if (!error) {
        FormData.value.menuIds = data
      }
    }
  }
)


/**
 * @description 子账号
 * @param {String} label
 * @param {String} value
 */
const DubordinateStatusDict = [
  {
    label: `可以`,
    value: `0`
  },
  {
    label: `不可用`,
    value: `1`
  }
]

/**
 * @description 账号状态
 * @param {String} label
 * @param {String} value
 */
const AccountStatusDict = [
  {
    label: `正常`,
    value: '0'
  },
  {
    label: `停用`,
    value: '1'
  }
]

getRoleUserEcho()
getEchoHospitalDepartment()
</script>

<template>
  <a-drawer v-model:open="openVModel" :closable="false" width="520">
    <!-- 标题 -->
    <template #title>
      <template v-if="FormData.userId">
        <div class="flex-1 flex items-center">
          <a-avatar :size="30" :src="FormData.avatar" />
          <span class="font-normal ml-2"
          >{{ FormData.nickName }} (用 cuserId:{{ FormData.userId }})
          </span>
        </div>
      </template>

      <template v-else>
        <div class="flex-1 flex justify-between items-center">
          <div>
            <span class="font-normal">{{ $t('routes.user.form.addTitle') }}</span>
          </div>
          <div class="flex items-center">
            <span class="font-normal text-xs mr-1">{{ $t('routes.user.form.addTip') }}</span>
            <QuestionCircleTwoTone />
          </div>
        </div>
      </template>
    </template>

    <!-- 表单 -->
    <template #default>
      <a-form ref="formRef" :model="FormData" :rules="rules" layout="vertical">
        <!-- 头像 -->
        <a-form-item
          :extra="$t('routes.user.form.uploadTip')"
          :label="$t('routes.user.form.avatar')"
          name="nickName"
        >
          <UploadImage v-model="FormData.avatar" />
        </a-form-item>

        <!-- 用户名称 -->
        <a-form-item
          :label="$t('routes.user.form.name')"
          :extra="$t('routes.user.form.nameTip')"
          name="nickName"
        >
          <a-input
            v-model:value="FormData.nickName"
            :placeholder="$t('routes.user.form.namePlaceholder')"
          />
        </a-form-item>

        <a-form-item :label="$t('routes.user.form.phone')" extra="" name="phonenumber">
          <a-input
            v-model:value="FormData.phonenumber"
            :maxlength="11"
            :placeholder="$t('routes.user.form.phonePlaceholder')"
            prefix=""
            show-count
            type="tel"
          />
        </a-form-item>

        <!-- 角色 -->
        <a-form-item :label="$t('routes.user.form.role')" :extra="$t('routes.user.form.roleTip')" name="roleIds">
          <a-select
            v-model:value="FormData.roleIds"
            :field-names="{ label: 'roleName', value: 'roleId' }"
            :options="cashbackData.data.sysRoles"
            :showSearch="false"
            mode="multiple"
            :placeholder="$t('routes.user.form.rolePlaceholder')"
            @select="handleOnChange"
          >
            <template v-if="cashbackData.loading" #notFoundContent>
              <a-spin size="small" />
            </template>
          </a-select>
        </a-form-item>

        <!-- 所属医院 -->
        <template v-if="FormData.roleIds.includes('108') || FormData.roleIds.includes('101')">
          <a-form-item
            :label="$t('routes.user.form.hospital')"
            name="hospitalId"
          >
            <a-select
              v-model:value="FormData.hospitalId"
              :field-names="{ label: 'hospitalName', value: 'hospitalId' }"
              :options="hosdepData.hospitalList"
              :placeholder="$t('routes.user.form.hospitalPlaceholder')"
            >
              <template #dropdownRender="{ menuNode: menu }">
                <v-nodes :vnodes="menu" />
                <a-divider style="margin: 4px 0" />
                <a-space style="padding: 4px 8px">
                  <a-input
                    ref="inputHospitalRef"
                    v-model:value="hosdepData.queryParams.hospitalName"
                    :placeholder="$t('routes.user.form.addhospitalPlaceholder')"
                  />
                  <a-button type="text" @click="handleAddHospital">
                    <!--                    <template #icon>-->
                    <!--                      <plus-outlined />-->
                    <!--                    </template>-->
                    {{$t('routes.user.form.addHospital')}}
                  </a-button>
                </a-space>
              </template>
            </a-select>
          </a-form-item>
        </template>


        <!-- 所属科室 -->
        <template
          v-if="
            FormData.roleIds.includes('108') ||
            FormData.roleIds.includes('109') ||
            FormData.roleIds.includes('101')
          "
        >
          <a-form-item :label="$t('routes.user.form.department')" extra="" name="classificationId">
            <a-select
              v-model:value="FormData.classificationId"
              :field-names="{
                label: 'classificationName',
                value: 'classificationId',
              }"
              :options="hosdepData.sectionList"
              :placeholder="$t('routes.user.form.departmentPlaceholder')"
            >
              <template #dropdownRender="{ menuNode: menu }">
                <v-nodes :vnodes="menu" />
                <a-divider style="margin: 4px 0" />
                <a-space style="padding: 4px 8px">
                  <a-input
                    ref="inputSectionRef"
                    v-model:value="hosdepData.queryParams.classificationName"
                    :placeholder="$t('routes.user.form.addDepartmentPlaceholder')"
                  />
                  <a-button type="text" @click="handleAddSection">
                    <!--                      <template #icon>-->
                    <!--                        <plus-outlined />-->
                    <!--                      </template>-->
                    {{$t('routes.user.form.addDepartment')}}
                  </a-button>
                </a-space>
              </template>
            </a-select>
          </a-form-item>
        </template>

        <!-- 菜单权限 -->
        <a-form-item v-if="true" :label="$t('routes.user.form.permissions')" extra="" name="menuIds">
          <a-tree
            ref="treeRef"
            v-model:checkedKeys="FormData.menuIds"
            :checkStrictly="false"
            :checkable="true"
            :fieldNames="{ children: 'children', title: 'label', key: 'id' }"
            :tree-data="cashbackData.data.menusTreeSelects"
          />
        </a-form-item>


        <!-- 添加子账号 -->
        <a-form-item :label="$t('routes.user.form.subAccount')" name="subordinate">
          <a-radio-group v-model:value="FormData.subordinate">
            <a-radio
              v-for="item in DubordinateStatusDict"
              :key="item.value"
              :value="item.value"
            >{{ item.label }}
            </a-radio
            >
          </a-radio-group>
        </a-form-item>

        <!-- 账号状态 -->
        <a-form-item :label="$t('routes.user.form.accountStatus')" extra="" name="status">
          <a-radio-group v-model:value="FormData.status">
            <a-radio
              v-for="item in AccountStatusDict"
              :key="item.value"
              :value="item.value"
            >{{ item.label }}
            </a-radio
            >
          </a-radio-group>
        </a-form-item>

        <!-- 备注 -->
        <a-form-item :label="$t('routes.user.form.remark')" name="remark">
          <a-textarea
            v-model:value="FormData.remark"
            :auto-size="{ minRows: 3, maxRows: 6 }"
            :placeholder="$t('routes.user.form.remarkPlaceholder')"
          />
        </a-form-item>

      </a-form>
    </template>

    <template #footer>
      <div class="flex justify-end">
        <a-space>
          <a-button type="primary" @click="handleUserSubmit(formRef)">确定</a-button>
        </a-space>
      </div>
    </template>
  </a-drawer>

</template>

<style lang="less" scoped>

</style>
